<?php
namespace app\api\controller;
use app\api\controller\BaseController;
use app\common\errcode\ApiErrCode;
use app\common\errcode\ApiErrMsg;
use think\Loader;

class VoiceController extends BaseController
{
    protected $access_token_url = "https://xc.souxiu.cn/json/Intelligent_Speech_Interaction.json";

    protected $speech_ai_url    = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts";

    protected $usageModel;

    public function __construct()
    {
        parent::__construct();
        $this->usageModel = new \app\api\model\UsageModel();
    }

    /**
     * 语音合成
     * @param int       $toolid         工具id
     * @param int       $catid          工具分类id
     * @param string    $text           文本
     * @param string    $format         音频编码格式，支持PCM/WAV/MP3格式。默认值为mp3
     * @param string    $sample_rate    音频采样率，支持16000 Hz和8000 Hz，默认值：16000 Hz
     * @param string    $voice          发音人，默认值：xiaoyun
     * @param int       $volume         音量，取值范围：0~100，默认值：50
     * @param int       $speech_rate    语速，取值范围：-500~500，默认值：0
     * @param int       $pitch_rate     语调，取值范围：-500~500，默认值：0
     */
    public function create()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->post();
                $validate = Loader::validate('Tool');
                $check = $validate->scene('voice')->check($data);
                if(!$check) return $this->jsonJump(ApiErrCode::PARAM_ERROR,ApiErrMsg::PARAM_ERROR.','.$validate->getError());  
                $token = httpRequest($this->access_token_url);
                if(isset($token['code']) && isset($token['msg']) && $token['code'] == 200 && $token['msg'] == 'success'){
                    $params = [
                        'appkey'        => Config('aliyunappkey'),
                        'token'         => $token['data'][0]['token'],
                        'text'          => $data['text'],
                        'format'        => $data['format'],
                        'sample_rate'   => $data['sample_rate'],
                        'voice'         => isset($data['voice']) ? $data['voice'] : 'xiaoyun',
                        'volume'        => isset($data['volume']) ? $data['volume'] : 50,
                        'speech_rate'   => isset($data['speech_rate']) ? $data['speech_rate'] : 0,
                        'pitch_rate'    => isset($data['pitch_rate']) ? $data['pitch_rate'] : 0,
                    ];
                    $speech = $this->speech_ai_url . '?' . http_build_query($params);
                    $this->usageModel->write_behavior($this->userid,$data['toolid'],$data['catid']);
                    \app\common\model\CommonModel::recordLog($this->userid,'behavior',date('Y-m-d H:i:s'),'success','语音合成');
                    return $this->jsonJump(ApiErrCode::SUCCESS,ApiErrMsg::SUCCESS,['voice_url' => $speech]);
                }else{
                    $this->usageModel->write_behavior($this->userid,$data['toolid'],$data['catid']);
                    \app\common\model\CommonModel::recordLog($this->userid,'behavior',date('Y-m-d H:i:s'),'fail',isset($token['sub_msg']) ? $token['sub_msg'] : '获取token失败');
                    return $this->jsonJump(ApiErrCode::SPEECH_AI_FAIL,ApiErrMsg::SPEECH_AI_FAIL . ',' . isset($token['sub_msg']) ? $token['sub_msg'] : '获取token失败');    
                }  
            }        
        } catch (\Exception $e) {
            \app\common\model\CommonModel::recordLog($this->userid,'abnormal',date('Y-m-d H:i:s'),'warning',$e->getMessage());
            return $this->jsonJump(ApiErrCode::SYSTEM_ERROR,ApiErrMsg::SYSTEM_ERROR . ',错误信息:'. $e->getMessage());
        }    
    }
    
}